package com.cardbaobao.cardbabyclient.ui.activity;

import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.AgreementWebViewActivity;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.model.MessageList;
import com.cardbaobao.cardbabyclient.model.dao.HaveReadMessageDao;
import com.cardbaobao.cardbabyclient.model.result.MessageListResult;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.DensityUtil;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.utils.UmengEventUtils;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.cardbaobao.cardbabyclient.widget.refresh.FooterLoadMore;
import com.gyf.barlibrary.ImmersionBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by jiangzx on 2017/3/30.
 * 我的-我的消息  消息中心
 */
public class MineMessageActivity extends BaseActivity {
    private static final int PAGE_START = 1;
    @BindView(R.id.title_bar)
    TitleBar titleBar;

    @BindView(R.id.srLayout)
    SmartRefreshLayout srLayout;
    @BindView(R.id.footerLoadMore)
    FooterLoadMore footerLoadMore;

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;

    private int page = 1;
    private boolean isLoading;

    private List<MessageList.Message> messages = new ArrayList<>();
    private MessageAdapter adapter;

    private List<Long> haveReadMessages;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImmersionBar.with(this).statusBarDarkFont(true,Constant.STATUS_BAR_FONT_ALPHA).init();
        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mCurrentPageId= Self.Page.app_message_center_page;

        footerLoadMore.setStateNoMoreDataStr("没有更多数据了");
        footerLoadMore.setStateNoMoreData();

        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new MessageAdapter();

        srLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {

            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = PAGE_START;
                loadData();
            }
        });

        HaveReadMessageDao dao = new HaveReadMessageDao();
        haveReadMessages = dao.getAllHaveReadMessage();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_message_center;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (messages.size() == 0) {
            loadData();
        }
        UmengEventUtils.pageEvent(mContext,
                ApplicationHelper.getApplicationContext().getString(R.string.event_0x020));
        GoogleAnalyticsUtil.setScreenName(Google.MINE_NEWS);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        HaveReadMessageDao dao = new HaveReadMessageDao();
        dao.clearHaveReadMessages();
        dao.insertHaveReadMessages(haveReadMessages);
    }

    private void loadData() {
        if (isLoading) {
            return;
        }
        isLoading = true;
        Observable<String> observable= Api.getMessageList(String.valueOf(page));
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
                isLoading = false;
                if(recyclerView.getAdapter()==null){
                    recyclerView.setAdapter(adapter);
                }
                srLayout.finishRefresh();
                srLayout.finishLoadmore();
                srLayout.setLoadmoreFinished(true);
            }

            @Override
            public void onError(Throwable e) {
                page--;
                if (page < PAGE_START) {
                    page = PAGE_START;
                }
                if(recyclerView.getAdapter()==null){
                    recyclerView.setAdapter(adapter);
                }
            }

            @Override
            public void onNext(String s) {
                MessageListResult listResult = JsonUtil.json2Object(s, MessageListResult.class);
                if (listResult != null) {
                    if (listResult.getCode() == Constant.SUC_CODE) {
                        if (listResult.getData() != null) {
                            List<MessageList.Message> temp = listResult.getData().getDataList();
                            if (temp != null) {
                                if (temp.size() > 0) {
                                    if (page == PAGE_START) {
                                        messages.clear();
                                    }
                                    messages.addAll(temp);
                                    adapter.notifyDataSetChanged();
//                                    canLoadMore=true;
//                                    footer.setStatePreLoading();
                                } else {
                                    //没有更多数据了
//                                    canLoadMore=false;
//                                    footer.setStateNoMoreData();
                                }
                            }
                        }
                    } else {
                        ToastUtil.showToast(listResult.getMsg());
                    }
                }
            }
        });
    }

    private class MessageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        private static final int TYPE_CONTENT = 1;
        private static final int TYPE_NO_DATA = 2;
        private ShapeDrawable unReadBgDrawable;
        private ShapeDrawable haveReadBgDrawable;
        private int margin26;
        private int margin30;

        private MessageAdapter() {
            unReadBgDrawable = new ShapeDrawable(new OvalShape());
            unReadBgDrawable.getPaint().setColor(0xff6cc2fc);

            haveReadBgDrawable = new ShapeDrawable(new OvalShape());
            haveReadBgDrawable.getPaint().setColor(0xfffc6745);

            margin26 = DensityUtil.dp2px(13);
            margin30 = DensityUtil.dp2px(15);
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            if (viewType == TYPE_CONTENT) {
                View itemView = inflater.inflate(R.layout.item_message, parent, false);
                return new Holder(itemView);
            }
            if (viewType == TYPE_NO_DATA) {
                View itemView = inflater.inflate(R.layout.item_no_data, parent, false);
                return new NoDataHolder(itemView);
            }
            return null;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if (holder instanceof Holder) {
                final MessageList.Message message = messages.get(position);
                Holder h = (Holder) holder;
                RecyclerView.MarginLayoutParams params =
                        (RecyclerView.MarginLayoutParams) h.itemView.getLayoutParams();
                params.topMargin = margin30;
                params.leftMargin = margin26;
                params.rightMargin = margin26;
                h.tvContent.setText(message.getOutline());
                h.tvDate.setText(message.getCreateTime());
                h.tvTitle.setText(message.getTitle());
                if (haveReadMessages.contains(message.getID())) {
                    h.tvState.setText("已读");
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        h.tvState.setBackground(haveReadBgDrawable);
                    } else {
                        h.tvState.setBackgroundDrawable(haveReadBgDrawable);
                    }
                } else {
                    h.tvState.setText("未读");
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                        h.tvState.setBackground(unReadBgDrawable);
                    } else {
                        h.tvState.setBackgroundDrawable(unReadBgDrawable);
                    }
                }
                h.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        long messageId = message.getID();
                        if (!haveReadMessages.contains(messageId)) {
                            haveReadMessages.add(messageId);
                            notifyDataSetChanged();
                        }
                        SelfUtils.buriedClickData(Self.Action.app_click_msg_item,
                                Self.Action.app_click_msg_item_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                mPrePageId);
                        initIntent();
                        mIntent.setClass(mContext, AgreementWebViewActivity.class);
                        mIntent.putExtra(AgreementWebViewActivity.WEB_TITLE_S,
                                "消息详情");
                        mIntent.putExtra(AgreementWebViewActivity.WEB_URL_S,
                                URLUtil.MESSAGE_DETAIL + messageId);
                        mIntent.putExtra(AgreementWebViewActivity.WEB_TYPE_I,
                                6);
                        mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                        startActivity(mIntent);
                    }
                });
            }
        }

        @Override
        public int getItemCount() {
            return messages.size() == 0 ? 1 : messages.size();
        }

        @Override
        public int getItemViewType(int position) {
            return messages.size() == 0 ? TYPE_NO_DATA : TYPE_CONTENT;
        }
    }

    private class Holder extends RecyclerView.ViewHolder {
        private TextView tvState;
        private TextView tvTitle;
        private TextView tvDate;
        private TextView tvContent;

        private Holder(View itemView) {
            super(itemView);
            tvState = (TextView) itemView.findViewById(R.id.tv_message_state);
            tvTitle = (TextView) itemView.findViewById(R.id.tv_message_title);
            tvDate = (TextView) itemView.findViewById(R.id.tv_message_date);
            tvContent = (TextView) itemView.findViewById(R.id.tv_message_content);
        }
    }

    private class NoDataHolder extends RecyclerView.ViewHolder {
        private NoDataHolder(View itemView) {
            super(itemView);
            itemView.setVisibility(View.VISIBLE);
        }
    }
}
